package org.emp.service.impl;

import org.emp.common.LoginErrorCode;
import org.emp.common.Result;
import org.emp.exception.LoginException;
import org.emp.mapper.LoginMapper;
import org.emp.pojo.dto.AdminLoginDTO;
import org.emp.pojo.dto.EmpLoginDTO;

import org.emp.pojo.entity.Admin;
import org.emp.pojo.entity.Emp;
import org.emp.service.LoginService;
import org.emp.utils.JwtUtils;
import org.emp.utils.PasswordEncryptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 加油
 *
 * @author konglingfeng
 * @date 2025/8/9
 * @desc
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private LoginMapper loginMapper;

    @Override
    public Result<String> findEmpByEmUsername(EmpLoginDTO empLoginDto) {
        Emp emp = loginMapper.findEmpByEmUsername(empLoginDto);
        System.out.println(emp);
        if (emp == null) {
            throw new LoginException(LoginErrorCode.USERNAME_ERROR,"用户不存在");
        }
        String password = PasswordEncryptionUtils.md5(empLoginDto.getPassword());
        if (!emp.getPassword().equals(password)) {
            throw new LoginException(LoginErrorCode.PASSWORD_ERROR,"密码错误");
        }
        Map<String,Object> claims=new HashMap<>();
        claims.put("id", emp.getEno());
        claims.put("username", emp.getEmUsername());
        String jwt= JwtUtils.generateJwt(claims);
        return Result.success("登录成功",jwt);
    }

    @Override
    public Result<String> findAdminByEmUsername(AdminLoginDTO adminLoginDTO) {
        Admin admin = loginMapper.findAdminByEmUsername(adminLoginDTO);
        System.out.println(admin);
        if (admin == null) {
            throw new LoginException(LoginErrorCode.USERNAME_ERROR,"用户不存在");
        }
        String password = PasswordEncryptionUtils.md5(adminLoginDTO.getPassword());
        if (!admin.getPassword().equals(password)) {
            throw new LoginException(LoginErrorCode.PASSWORD_ERROR,"密码错误");
        }
        Map<String,Object> claims=new HashMap<>();
        claims.put("id", admin.getAdNo());
        claims.put("username", admin.getAdUsername());
        String jwt= JwtUtils.generateJwt(claims);
        return Result.success("登录成功",jwt);
    }


}
